<!DOCTYPE html>
<html lang="zh">

<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no" />
    <title>资源配置 - 8282管理系统</title>
    <link rel="icon" href="favicon.ico" type="image/ico">
    <meta name="keywords" content="8282管理系统,egg.js,Bootstrap,JQ,node.js,后台模板,后台管理系统">
    <meta name="description" content="8282管理系统是基于Egg.js+LightYear构建的后台管理系统。">
    <meta name="author" content="cadcamzy">
    <link href="/public/css/bootstrap.min.css" rel="stylesheet">
    <link href="/public/css/materialdesignicons.min.css" rel="stylesheet">
    <link href="/public/js/x-editable/1.5.1/bootstrap3-editable/css/bootstrap-editable.min.css" rel="stylesheet">
    <link href="/public/js/jquery-treegrid/jquery.treegrid.min.css" rel="stylesheet">
    <link href="/public/js/jquery-fonticonpicker/jquery.fonticonpicker.min.css" rel="stylesheet">
    <link href="/public/js/jquery-fonticonpicker/jquery.fonticonpicker.bootstrap.min.css" rel="stylesheet" />
    <link href="/public/css/animate.css" rel="stylesheet">
    <link href="/public/css/style.min.css" rel="stylesheet">

</head>

<body>
    <div class="container-fluid p-t-15">

        <div class="row">
            <div class="col-lg-12">
                <div class="card">
                    <div class="card-header">
                        <h4>资源配置</h4>
                    </div>
                    <div class="card-body">
                        <div id="toolbar" class="toolbar-btn-action">
                            <button id="btn_add" type="button" class="btn btn-primary m-r-5">
                                <span class="mdi mdi-plus" aria-hidden="true"></span>新增
                            </button>
                            <button id="btn_edit" type="button" class="btn btn-success m-r-5">
                                <span class="mdi mdi-check" aria-hidden="true"></span>修改
                            </button>
                            <button id="btn_delete" type="button" class="btn btn-danger m-r-5">
                                <span class="mdi mdi-window-close" aria-hidden="true"></span>删除
                            </button>
                            <button id="btn_search" type="button" class="btn btn btn-purple m-r-5">
                                <span class="mdi mdi-search-web" aria-hidden="true"></span>搜索
                            </button>
                            <button id="btn_refresh" type="button" class="btn btn-secondary m-r-5"
                                onclick="javascript:window.location.href=window.location.href;">
                                <span class="mdi mdi-refresh" aria-hidden="true"></span>刷新
                            </button>
                        </div>
                        <div class="form-group" style="height: 490px;overflow: auto; margin-top: 10px;">
                            <table id="db_table" class="tree-table"></table>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
    <div id="search_modal" class="modal fade" tabindex="-2" role="dialog" aria-labelledby="myLargeModalLabel"
        data-backdrop="static" data-keyboard="false">
        <div class="modal-dialog" role="document">
            <div class="modal-content">
                <div class="modal-header">
                    <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span
                            aria-hidden="true">×</span></button>
                    <h4 class="modal-title" id="myLargeModalLabel2">条件搜索</h4>
                </div>
                <div class="modal-body">
                    <div class="form-group" id="search_tags">
                        <span class="label label-outline-purple">搜索条件</span>
                    </div>
                    <div class="form-group">
                        <label class="control-label" for="search_field">字段:</label>
                        <select class="form-control" id="search_field" size="1"></select>
                    </div>
                    <div class="form-group">
                        <label class="control-label" for="search_text">搜索内容:</label>
                        <input class="form-control" type="text" id="search_text" placeholder="请输入搜索内容..">
                        <button id="btn_search_reset" type="button" class="btn btn-danger m-t-10 m-r-5">重置条件</button>
                        <button id="btn_search_add" type="button" class="btn btn-primary m-t-10 m-r-5">添加条件</button>
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-default" data-dismiss="modal">取消</button>
                    <button id="btn_search_submit" type="button" class="btn btn-purple">搜索</button>
                </div>
            </div>
        </div>
    </div>
    <div id="new_modal" class="modal fade" tabindex="-1" role="dialog" aria-labelledby="myLargeModalLabel"
        data-backdrop="static" data-keyboard="false">
        <div class="modal-dialog" role="document">
            <div class="modal-content">
                <div class="modal-header">
                    <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span
                            aria-hidden="true">×</span></button>
                    <h4 class="modal-title" id="myLargeModalLabel">新增资源</h4>
                </div>
                <div class="modal-body">
                    <div class="form-group">
                        <label class="control-label" for="description">描述:</label>
                        <input class="form-control" type="text" id="description" name="description"
                            placeholder="请输入描述信息..">
                    </div>
                    <div class="form-group">
                        <label class="control-label" for="router_id">关联路由:</label>
                        <select class="form-control" id="router_id" name="router_id" size="1" onchange="routerChange()">
                            {% for router in routers %}
                            <option value="{{ router.id }}" data-title="{{ router.title }}" data-path="{{ router.path }}"
                                data-controller="{{ router.controller_name }}">{{ router.title }}</option>
                            {% else %}
                            <option value="">请选择</option>
                            {% endfor %}
                        </select>
                    </div>
                    <div class="form-group">
                        <label class="control-label" for="router_name">路由名称:</label>
                        <input class="form-control" type="text" id="router_name" name="router_name"
                            placeholder="请输入路由名称.." readonly>
                    </div>
                    <div class="form-group">
                        <label class="control-label" for="controller_name">控制器名称:</label>
                        <input class="form-control" type="text" id="controller_name" name="controller_name"
                            placeholder="请输入控制器名称.." readonly>
                    </div>
                    <div class="form-group">
                        <label class="control-label" for="url">路径:</label>
                        <input class="form-control" type="text" id="url" name="url" placeholder="请输入路径.." readonly>
                    </div>
                    <div class="form-group">
                        <label class="control-label" for="type">类型:</label>
                        <select class="form-control" id="type" name="type" size="1">
                            <option value="menu">菜单</option>
                            <option value="page">页面</option>
                            <option value="button">按键</option>
                            <option value="api">接口</option>
                        </select>
                    </div>
                    <div class="form-group">
                        <label class="control-label" for="icon">图标(只作用于菜单和页面):</label>
                        <input class="form-control" type="text" id="icon" name="icon"/>
                    </div>
                    <div class="form-group">
                        <label class="control-label" for="pid">PID:</label>
                        <select class="form-control" id="pid" name="pid" size="1">
                            {% for resource in resources %}
                            <option value="{{ resource.id }}">{{ resource.routerDesc }}</option>
                            {% else %}
                            <option value="0">请选择</option>
                            {% endfor %}
                        </select>
                    </div>
                    <div class="form-group">
                        <label class="control-label" for="sort">排序:</label>
                        <input class="form-control" type="number" id="sort" name="sort" placeholder="请输入排序..">
                    </div>
                    <div class="form-group">
                        <label class="control-label" for="status">状态:</label>
                        <select class="form-control" id="status" name="status" size="1">
                            <option value="1">启用</option>
                            <option value="0">禁用</option>
                        </select>
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-default" data-dismiss="modal">关闭</button>
                    <button id="btn_save" type="button" class="btn btn-primary">点击保存</button>
                </div>
            </div>
        </div>
    </div>

    <script type="text/javascript" src="/public/js/jquery.min.js"></script>
    <script type="text/javascript" src="/public/js/bootstrap.min.js"></script>
    <script type="text/javascript" src="/public/js/perfect-scrollbar.min.js"></script>
    <script type="text/javascript" src="/public/js/bootstrap-table/bootstrap-table.min.js"></script>
    <script type="text/javascript" src="/public/js/bootstrap-table/bootstrap-table-zh-CN.min.js"></script>
    <!--行内编辑插件-->
    <script type="text/javascript" src="/public/js/x-editable/1.5.1/bootstrap3-editable/js/bootstrap-editable.min.js"></script>
    <script type="text/javascript" src="/public/js/bootstrap-table/extensions/editable/bootstrap-table-editable.min.js"></script>

    <script type="text/javascript" src="/public/js/jquery-treegrid/jquery.treegrid.min.js"></script>
    <script type="text/javascript" src="/public/js/bootstrap-table/extensions/treegrid/bootstrap-table-treegrid.min.js"></script>

    <script type="text/javascript" src="/public/js/jquery-fonticonpicker/jquery.fonticonpicker.min.js"></script>

    <script type="text/javascript" src="/public/js/main.min.js"></script>
    <script type="text/javascript">
        $().ready(function() {
            let icon = $('#icon').fontIconPicker({
                theme: 'fip-bootstrap'
            });
            const icons = JSON.parse(`{{ icons | safe }}`);
            let fontello_json_icons = [];
            $.each(icons.glyphs, function(i, v) {
                fontello_json_icons.push( v.css );
            });
            icon.setIcons(fontello_json_icons);
        });

        const columns = [
            { checkbox: true },    // 是否显示复选框
            { field: 'id', title: 'ID', sortable: true },    // 是否排序
            { field: 'pid', title: 'PID' },    // 是否排序
            { field: 'routerDesc', title: '资源描述' },
            { field: 'router.routerName', title: '路由名称' },
            { field: 'router.controller_name', title: '动作名称' },
            { field: 'type', title: '类型' },
            { field: 'router.path', title: '路径' },
            { field: 'sort', title: '排序' },
            {
                field: 'status', title: '状态', editable: {
                    type: 'select',
                    title: "状态",
                    pk: 1,
                    source: [
                        { value: 0, text: '禁用' },
                        { value: 1, text: '正常' }
                    ],
                    noeditFormatter: function (value, row, index) {
                        var result;

                        if (value == '0' || value == '禁用') {
                            result = { filed: "status", value: "禁用", class: "label label-danger" };
                        } else if (value == '1' || value == '正常') {
                            result = { filed: "status", value: "正常", class: "label label-success" };
                        }

                        return result; // 这里对bootstrap-table-editable.min.js做了一些修改，让其能接收class
                    },
                    // 可以按列分开做保存，也可以用后面的onEditableSave
                    url: "/system/resources/0",
                    ajaxOptions: {
                        type: 'put',
                        dataType: 'json'
                    }, // 默认是post方式提交,这里因为跨域,改成get
                    success: function (response, newValue) {
                        if (response.code == '200') {
                            // 这里的状态显示有自定义样式区分，做单元格更新
                            $('#tb_departments').bootstrapTable('updateCellById', { id: response.id, field: 'status', value: newValue });
                        } else {
                            return response.msg;
                        }
                    },
                    highlight: false
                }
            },
            {
                field: 'operate', title: '操作', formatter: btnGroup,  // 自定义方法
                events: {
                    'click .edit-btn': function (event, value, row, index) {
                        editUser(row.id);
                    },
                    'click .del-btn': function (event, value, row, index) {
                        delUser(row.id);
                    }
                }
            }
        ]

        //绑定路由改变，自动赋值相关项
        let routerChange = function() {
            const opt = $("#router_id").find('option:selected');
            const controller = opt.attr('data-controller');
            $("#router_name").val(opt.attr('data-title'));
            $("#controller_name").val(controller);
            $("#url").val(opt.attr('data-path'));
            const resType = {
                page: 'page', index: 'api', create: 'button', show: 'api', update: 'api', destory: 'button',
            };
            $("#type").val(resType[controller.split('.').pop()]);
            $("#description").val(opt.attr('data-title'));
        };

        const db_table = $('#db_table');
        const search_modal = $("#search_modal");
        const new_modal = $("#new_modal");

        let fieldName = {};
        $("#btn_search").click(function () {
            let options = [];
            new_modal.find('[name]').each(function () {
                const _this = $(this);
                const label = _this.prev().text().replace(':', '').split('(')[0];
                const field = _this.attr('name');
                options.push(`<option value="${field}">${label}</option>`);
                fieldName[field] = label;
            });
            $("#search_field").html(options.join(''));
            search_modal.modal('show');
        });

        let searchParams = {};
        $("#btn_search_add").click(function () {
            // 添加搜索条件
            const field = $("#search_field").val();
            const text = $("#search_text").val();
            const search_tags = $("#search_tags");
            searchParams[field] = text;
            search_tags.html('');
            for (let key in searchParams) {
                const template = `<span class="label label-outline-${randomColor()} mr-r-4">${fieldName[key]}:${searchParams[key]}</span>`;
                search_tags.append(template);
            }
        });

        $("#btn_search_reset").click(function () {
            searchParams = {};
            $("#search_tags").html('<span class="label label-outline-purple">搜索条件</span>');
        })

        // 构建Bootstraptable 的查询参数
        let queryParams = function (params) {
            let temp = {
                limit: params.limit,         // 每页数据量
                offset: params.offset,       // sql语句起始索引
                page: (params.offset / params.limit) + 1,
                sort: params.sort,           // 排序的列名
                sortOrder: params.order      // 排序方式'asc' 'desc'
            };
            return $.extend({}, temp, searchParams);
        };

        $("#btn_search_submit").click(function () {
            // 提交搜索
            if ('{}' === JSON.stringify(searchParams)) {
                parent.lightyear.notify('搜索条件为空，请先添加！', 'warning', 3500, 'mdi mdi-emoticon-devil', 'top', 'center');
            } else {
                db_table.bootstrapTable('refresh');
                search_modal.modal('hide');
            }
        });

        let edit_status = 'new';
        let editUser = function (id) {
            edit_status = 'edit';
            $("#myLargeModalLabel").html('编辑资源');
            $.ajax({
                type: "get",
                url: "/system/resources/" + id,
                data: "",
                dataType: 'json',
                success: function (data, status) {
                    if (data.code == '200') {
                        // 这里的状态显示有自定义样式区分，做单行的更新
                        const json = data.data;
                        new_modal.find('[name]').each(function () {
                            const _this = $(this);
                            const field = _this.attr('name');
                            if (field === 'status') _this.val(json[field] ? "1" : "0");
                            else _this.val(json[field]);
                        });
                        new_modal.modal('show');
                    } else {
                        parent.lightyear.notify(data.msg, 'danger', 3500, 'mdi mdi-emoticon-dead', 'top', 'center');
                    }
                },
                error: function () {
                    alert('获取指定数据失败, 请稍后尝试！');
                }
            });
        };

        let delUser = function (id) {
            parent.$.confirm({
                title: '删除确认', type: 'red', typeAnimated: true,
                content: `你是否确认删除编号：[${id}] 的账号？`,
                buttons: {
                    confirm: {
                        text: '确认',
                        action: function () {
                            $.ajax({
                                type: "delete",
                                url: "/system/resources/" + id,
                                data: "",
                                dataType: 'json',
                                success: function (data, status) {
                                    if (data.code == '200') {
                                        // 这里的状态显示有自定义样式区分，做单行的更新
                                        parent.lightyear.notify(data.msg, 'success', 3500, 'mdi mdi-emoticon-happly', 'top', 'center');
                                        db_table.bootstrapTable('refresh');
                                        new_modal.modal('hide');
                                    } else {
                                        parent.lightyear.notify(data.msg, 'danger', 3500, 'mdi mdi-emoticon-dead', 'top', 'center');
                                    }
                                },
                                error: function () {
                                    parent.lightyear.notify('发生错误，请稍后尝试！', 'danger', 3500, 'mdi mdi-emoticon-dead', 'top', 'center');
                                }
                            });
                        }
                    },
                    cancel: { text: '取消', },
                }
            });
        };

        db_table.bootstrapTable({
            url: '/system/resources',
            method: 'get',
            dataType: 'json',        // 因为本示例中是跨域的调用,所以涉及到ajax都采用jsonp,
            idField: 'id',
            uniqueId: 'id',
            data: { page: 0, sortOrder: 'asc', limit: 9999 },
            queryParams: queryParams,     // 传递参数
        //    clickToSelect: true,     // 是否启用点击选中行
        //    toolbar: '#toolbar',
            columns: columns,
        //    showRefresh: true,         // 是否显示刷新按钮
            singleSelect: true,         // 禁止多选
            treeShowField: 'routerDesc',
            parentIdField: 'pid',
            
            onResetView: function(data) {
                db_table.treegrid({
                    initialState: 'collapsed', // 所有节点都折叠
                    treeColumn: 3,
                    //expanderExpandedClass: 'mdi mdi-folder-open',  // 可自定义图标样式
                    //expanderCollapsedClass: 'mdi mdi-folder',
                    onChange: function() {
                        db_table.bootstrapTable('resetWidth');
                    }
                });
                
                // 只展开树形的第一集节点
                db_table.treegrid('getRootNodes').treegrid('expand');
            },
        });

        // 操作按钮
        function btnGroup() {
            let html =
                '<a href="#!" class="btn btn-xs btn-default m-r-5 edit-btn" title="编辑" data-toggle="tooltip"><i class="mdi mdi-pencil"></i></a>' +
                '<a href="#!" class="btn btn-xs btn-default del-btn" title="删除" data-toggle="tooltip"><i class="mdi mdi-window-close"></i></a>';
            return html;
        }

        new_modal.on('hide.bs.modal', function () {
            // 关闭模态框时取消选中行
            db_table.bootstrapTable('uncheckAll');
        });

        // 新增
        $("#btn_add").click(function () {
            edit_status = 'new';
            $("#myLargeModalLabel").html('新增资源');
            new_modal.find('[name]').each(function () {
                const _this = $(this);
                _this.val('');
            });
            new_modal.modal('show');
        });
        // 编辑
        $("#btn_edit").click(function () {
            //得到表格选中行的id
            const rows = db_table.bootstrapTable('getSelections');
            if (!rows[0] || !rows[0].id) {
                parent.lightyear.notify('请先选择一条记录！', 'danger', 3500, 'mdi mdi-emoticon-dead', 'top', 'center');
                return;
            }
            const id = rows[0].id;
            if (!id) {
                parent.lightyear.notify('选中的数据不正确！', 'danger', 3500, 'mdi mdi-emoticon-dead', 'top', 'center');
            } else {
                editUser(id);
            }
        });

        $("#btn_save").click(function () {
            let data = {};
            new_modal.find('[name]').each(function () {
                const _this = $(this);
                const field = _this.attr('name');
                if (field === 'status') data[field] = _this.val() === "1" ? true : false;
                data[field] = _this.val();
            });

            if (edit_status === 'new') {
                // 新增
                $.ajax({
                    type: "post",
                    url: "/system/resources",
                    data: data,
                    dataType: 'json',
                    success: function (data, status) {
                        if (data.code === 201) {
                            parent.lightyear.notify(data.msg, 'success', 3500, 'mdi mdi-emoticon-happly', 'top', 'center');
                            db_table.bootstrapTable('refresh');
                        }else {
                            parent.lightyear.notify(data.msg, 'danger', 3500, 'mdi mdi-emoticon-danger', 'top', 'center');
                        }
                        new_modal.modal('hide');
                    },
                    error: function () {
                        parent.lightyear.notify('修改失败，请稍后再试', 'danger', 3500, 'mdi mdi-emoticon-danger', 'top', 'center');
                    }
                });
            } else if (edit_status === 'edit') {
                //编辑
                const rows = db_table.bootstrapTable('getSelections');
                const id = rows[0].id;
                $.ajax({
                    type: "put",
                    url: "/system/resources/" + id,
                    data: data,
                    dataType: 'json',
                    success: function (data, status) {
                        if (data.code == '200') {
                            // 这里的状态显示有自定义样式区分，做单行的更新
                            parent.lightyear.notify(data.msg, 'success', 3500, 'mdi mdi-emoticon-happly', 'top', 'center');
                            db_table.bootstrapTable('refresh');
                            new_modal.modal('hide');
                        } else {
                            parent.lightyear.notify(data.msg, 'danger', 3500, 'mdi mdi-emoticon-danger', 'top', 'center');
                        }
                    },
                    error: function () {
                        alert('修改失败，请稍后再试');
                    }
                });
            }
        });

        $("#btn_delete").click(function () {
            const rows = db_table.bootstrapTable('getSelections');
            if (!rows[0] || !rows[0].id) {
                parent.lightyear.notify('请先选择一条记录！', 'danger', 3500, 'mdi mdi-emoticon-danger', 'top', 'center');
                return;
            }
            const { id, title } = rows[0];
            parent.$.confirm({
                title: '删除确认', type: 'red', typeAnimated: true,
                content: `你是否确认删除 [${title}] 的账号？`,
                buttons: {
                    confirm: {
                        text: '确认',
                        action: function () {
                            delUser(id);
                        }
                    },
                    cancel: { text: '取消', },
                }
            });
        });
    </script>
</body>

</html>